<template>
  <ElDialog v-model="visibleProxy" title="导入表格" width="560px" :close-on-click-modal="false">
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="110px">
      <ElFormItem label="应用名称" prop="app_name">
        <ElInput v-model="form.app_name" placeholder="请输入应用英文名，如 crm" />
      </ElFormItem>
      <ElFormItem label="Schema" prop="table_schema">
        <ElInput v-model="form.table_schema" placeholder="请输入数据库 schema，如 case_app" />
      </ElFormItem>
      <ElFormItem label="表名" prop="table_name">
        <ElSelect v-model="form.table_name" filterable remote clearable placeholder="请输入关键字搜索表名"
          :remote-method="handleSearchTables" :loading="searching">
          <ElOption v-for="opt in tableOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElSpace>
        <ElButton @click="handleCancel">取 消</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleSubmit">提 交</ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { importCode, type ImportRequest } from '@/api/code_generator/code'
import { searchTables, type TableOptionInfo } from '@/api/system/table'

interface Props {
  visible: boolean
}
interface Emits {
  (e: 'update:visible', val: boolean): void
  (e: 'submitted', payload: ImportRequest): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const visibleProxy = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

const formRef = ref()
const submitting = ref(false)
const searching = ref(false)
const tableOptions = ref<TableOptionInfo[]>([])

const form = reactive<ImportRequest>({
  app_name: '',
  table_schema: '',
  table_name: ''
})

const rules = {
  app_name: [{ required: true, message: '请输入应用英文名', trigger: 'blur' }],
  table_schema: [{ required: true, message: '请输入数据库schema', trigger: 'blur' }],
  table_name: [{ required: true, message: '请选择表名', trigger: 'change' }]
}

async function handleSearchTables(query: string) {
  if (!query) {
    tableOptions.value = []
    return
  }
  searching.value = true
  try {
    tableOptions.value = await searchTables(query)
  } finally {
    searching.value = false
  }
}

function resetForm() {
  form.app_name = ''
  form.table_schema = ''
  form.table_name = ''
  tableOptions.value = []
}

function handleCancel() {
  visibleProxy.value = false
  resetForm()
}

function validate(): Promise<boolean> {
  return new Promise((resolve) => {
    formRef.value?.validate((valid: boolean) => resolve(valid))
  })
}

async function handleSubmit() {
  const ok = await validate()
  if (!ok) return
  submitting.value = true
  try {
    await importCode(form)
    emit('submitted', { ...form })
    visibleProxy.value = false
    resetForm()
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped></style>